package com.intramirror.product.schedule;

import com.intramirror.product.mapper.PriceChangeRuleMapper;
import com.intramirror.product.service.IPriceRuleService;
import com.intramirror.product.utils.ConvertUtil;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@PropertySource(value = "classpath:${spring.profiles.active}/schedule.properties")
@Component
public class PriceRuleSnapshotSchedule {
    private static final Logger LOGGER = LoggerFactory.getLogger(PriceRuleSnapshotSchedule.class);
    private static final long ONE_MINUTE = 60 * 1000;
    private static int count = 0;

    private static Date lastUpdate = null;

    @Autowired
    PriceChangeRuleMapper priceChangeRuleMapper;

    @Autowired
    IPriceRuleService priceRuleService;

    @Autowired
    private BurstingManager burstingManager;

    @Value("${snapshot.minutes}")
    private Integer snapshotMinutes;

    public Integer getSnapshotMinutes() {
        return snapshotMinutes;
    }

    public void setSnapshotMinutes(Integer snapshotMinutes) {
        this.snapshotMinutes = snapshotMinutes;
    }

    @Scheduled(fixedDelay = ONE_MINUTE)
    public void fixedSnapshotJob() {
        if (count++ % snapshotMinutes != 0) {
            return;
        }

        LOGGER.info("===================================================================");
        LOGGER.info("===================Start to refresh price rule=====================");
        LOGGER.info("===================================================================");


        Date checkDate = new Date();
        if (lastUpdate == null) {
            // refresh 所有的更改记录
            burstingManager.refreshByDate(null);
        } else {
            // refresh > lastUpdate 的更改记录
            burstingManager.refreshByDate(lastUpdate);
        }
        lastUpdate = checkDate;


        Long start = System.currentTimeMillis();
        // 获取需要刷新的列表
        List<Map<String, Object>> unRefreshPriceRule = priceChangeRuleMapper.getUnRefreshPriceRule();
        for (Map<String, Object> row : unRefreshPriceRule) {
            try {
                priceRuleService.refreshSnapshotPrice(ConvertUtil.toLong(row.get("im_price_algorithm_id")),
                        ConvertUtil.toLong(row.get("price_change_rule_id")));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        LOGGER.info("It takes {}ms to refresh price rule.", System.currentTimeMillis() - start);
    }
}
